package com.crl.utils.deeplink
{
	import flash.external.*;
	import flash.utils.*;
	
	/**
	 * Utility class to handle address query string parameters.
	 * 
	 * from :
	 * com.floss.util.deeplink
	 */
	public class QueryString 
	{
		
		private static var paramsCache:Object;
		private static var hasp:Boolean;
		private static var read:Object;
		
		/**
		 * Test to see if there are deeplink parameters.
		 */
		public static function HasParams():Boolean
		{
			if(read)
				return hasp;
			
			var _queryString:String;
			try 
			{
				_queryString = ExternalInterface.call("window.location.search.substring", 1);
				if(_queryString)
				{
					hasp = true;
					return true;	
				}
				
			}catch(e:Error) { trace("Some error occured. ExternalInterface doesn't work in Standalone player."); }
			hasp = false;
			return false;
		}
		
		/**
		 * Read all parameters. Returns an associative array with each parameters.
		 * After you've called this once, the parameters are cached so further 
		 * reading doesn't actually make the ExternalInterface call.
		 * @param	Boolean		Whether or not to force an internal params cache update.
		 */
		public static function ReadParams(forceReread:Boolean = false):Object
		{
			if(read && !forceReread)
				return paramsCache;
			
			var _params:Object = {};
			var _queryString:String;
			try 
			{
				_queryString = ExternalInterface.call("window.location.search.substring", 1);
				if(_queryString)
				{
					var params:Array = _queryString.split('&');
					var length:uint = params.length;
					for (var i:uint=0,index:int=-1; i<length; i++) 
					{
						var kvPair:String = params[i];
						if((index = kvPair.indexOf("=")) > 0)
						{
							var key:String = kvPair.substring(0,index);
							var value:String = kvPair.substring(index+1);
							_params[key] = value;
						}
					}
				}
			}catch(e:Error) { trace("Some error occured. ExternalInterface doesn't work in Standalone player."); }
			paramsCache = _params;
			return _params;
		}
	}
}
